/**
 * Created by sxx on 2017/5/6.
 */
import "./index.less";
import httpurl from "../../../unit/common/js/httpurl";
import { splrTyp } from "../config.js";
import UserBasicInfoTpl from './tmpl/user_basic_info.handlebars';
import AptListTpl from './tmpl/attachment.handlebars';
import bankListTpl from './tmpl/bank_list.handlebars';
jQuery(document).ready(function() {

    App.init();
    let token = sessionStorage.getItem('token');

    let splrId = httpurl.uri.params.id;
    let canClick = true;

    const ApplyDetail = {
        comParm: '',
        regionList: '',
        init: function() {
            this.getData()
                .then(this.getRegionInfo)
                .then(this.getComParms)
                .then(this.renderBasicInfo)
                .then(this.renderAttachment);
        },

        // 获取地区信息
        getRegionInfo: function(data) {
            const self = ApplyDetail;
            return new Promise((resolve, reject) => {
                if (self.regionList) {
                    resolve(data);
                }

                const regionList = localStorage.getItem('regionList');
                if (regionList) {
                    self.regionList = JSON.parse(regionList);
                    resolve(data);
                } else {
                    $.ajax({
                        url: HOST_ADDR + '/cpmp/region/region_all',
                        type: 'get',
                        dataType: 'json',
                        contentType: "application/json",
                        success: function(resp) {
                            localStorage.setItem('regionList', JSON.stringify(resp));
                            self.regionList = resp;
                            resolve(data);

                        },
                        error: function(err) {
                            console.log(err);
                        }
                    });

                }
            });
        },

        getComParms(data) {
            const self = ApplyDetail;
            return new Promise((resolve, reject) => {
                const parmTyps = 'CPN_NTR,SPLR_TYP,IDST_TYP,GRUP_ACNT_GRUP';
                const url = HOST_ADDR + '/cpmp/comParm/getByParmTyps/' + parmTyps;
                $.ajax({
                    url: HOST_ADDR + '/cpmp/comParm/getByParmTyps/' + parmTyps,
                    type: 'get',
                    dataType: 'json',
                    //headers:{
                    //    'access_token': token,
                    //    'login_type': 'splr'
                    //},
                    contentType: 'application/json',
                    success: function(resp) {
                        self.comParm = resp;
                        resolve(data);
                    },
                    error: function(err) {
                        console.log(err);
                    }
                })
            })
        },
        //获取数据
        getData: function() {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: HOST_ADDR+'/cpmp/splrMng/splr/'+splrId,
                    type: 'get',
                    dataType: 'json',
                    headers: {
                        'access_token': token,
                        'login_type': 'ums'
                    },
                    contentType: "application/json",
                    success: function(resp) {
                        if (resp.success && resp.msgCod === 'S0002') {
                            console.log(resp);
                            resolve(resp);
                        } else {
                            alert(resp.msgInfo);
                        }
                    },
                    error: function(err) {
                        console.log(err);
                    }

                });

            });
        },

        // 渲染详情

        // 渲染用户基本信息
        renderBasicInfo(rsp) {
            const self = ApplyDetail;
            return new Promise((resolve, reject) => {
                let data = rsp.data;
                data.ptnrTypFmt = splrTyp[data.classification];
                if (!self.comParm) {
                    self.getComParms().then(() => {
                        data = self.formatData(data);
                        let basicInfoHtml = UserBasicInfoTpl({ data });
                        $('#J_basicInfo').html(basicInfoHtml);
                    })
                } else {
                    data = self.formatData(data);
                    let basicInfoHtml = UserBasicInfoTpl({ data });
                    $('#J_basicInfo').html(basicInfoHtml);
                }
                let aptList = data.splrApts;
                if (aptList.length > 0) {
                    $.each(aptList,function(index,item){
                        if (item.aptVal) {
                            item.addrFmt = HOST_ADDR + '/' + item.aptVal;
                        }
                    });

                    let aptListHtml = AptListTpl({ aptList });
                    $('.J_attachment').html(aptListHtml).closest('.row-fluid').removeClass('hidden');
                }
                let bankList = data.splrBnkAcnts;
                if (bankList.length > 0) {
                    let bankListHtml = bankListTpl({ bankList });
                    $('.J_bank').html(bankListHtml).closest('.row-fluid').removeClass('hidden');
                }
                resolve(rsp);
            });
        },
        renderAttachment(rsp) {
            return new Promise((resolve, reject) => {
                if (rsp.data.splrApts) {
                    console.log(rsp.data.splrApts);
                    $.each(resp.data.splrAtps,function(index,item){
                        console.log(HOST_ADDR + '/' + item.aptVal);
                    })
                }
            })
        },
        // 处理数据
        formatData(data) {
            let self = ApplyDetail;
            console.log(self.regionList);
            data.hasCreditCode = data.hasCreditCode == '1' ? '是' : '否';
            data.contact = data.contact ? data.contact : '';
            data.fullAddr = data.rgstAddr;
            let region, city, district;
            let regDate = new Date(data.regTim);
            if (data.region) {
                data.region = $.trim(data.region);
                region = self.regionList[data.region].name;
                city = data.city ? self.regionList[data.region].cities[$.trim(data.city)].name : '';
                district = (data.city && data.district) ? self.regionList[data.region].cities[$.trim(data.city)].towns[$.trim(data.district)].name : '';
                data.fullAddr = region + city + district + (data.rgstAddr ? data.rgstAddr : '');
            }
            data.fullTel = '';
            data.fullFax = '';
            if(data.telEx || data.telephone){
                if(data.telEx && data.telephone){
                    data.fullTel = data.telEx + ' - ' + data.telephone;
                }else{
                    data.fullTel = data.telEx ? data.telEx : data.telephone;
                }
            }
            if(data.faxEx || data.fax){
                if(data.faxEx && data.fax){
                    data.fullFax = data.faxEx + ' - ' + data.fax;
                }else{
                    data.fullFax = data.faxEx ? data.faxEx : data.fax;
                }
            }
            console.log(region);
            data.regTimFmt = `${regDate.getFullYear()}年${regDate.getMonth()+1}月${regDate.getDate()}日`;
            $.each(self.comParm.data.IDST_TYP,function(index,item){
                if (item.parmCod === data.idst1) {
                    console.log(item);
                    data.idst1 = item.parmVal;
                }
                if (item.parmCod === data.idst2) {
                    console.log(item);
                    data.idst2 = item.parmVal;
                }
            });
            $.each(self.comParm.data.SPLR_TYP,function(index,item){
                if (item.parmCod == data.ptnrTyp) {
                    data.ptnrTyp = item.parmVal;
                }
            });
            $.each(self.comParm.data.CPN_NTR,function(index,item){
                if (item.parmCod == data.cpnNtr) {
                    data.cpnNtr = item.parmVal;
                }
            });

            return data;
        },

    };

    ApplyDetail.init();
    $('.J_pass').off().on('click', function() {
        let data = {
            "splrId": splrId,
            "splrSts": "03"

        };
        if (canClick == true) {
            canClick = false;
            $.ajax({
                url: HOST_ADDR + `/cpmp/splrMng/changeStsForSplr`,
                type: 'post',
                dataType: 'json',
                data: JSON.stringify(data),
                headers: {
                    'access_token': token,
                    'splrId': splrId,
                    'login_type': 'ums'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        alert('准入申请成功');
                        canClick = true;
                        location.href = '/supplier_mng/supplier_apply_list_mng.html';
                    } else {
                        canClick = true;
                        alert(resp.msgInf);
                        location.href = '/supplier_mng/supplier_apply_list_mng.html';

                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });


        }
        console.log('clicked');
    })
    $('.J_fail').off().on('click', function() {
        let data = {
            "splrId": splrId,
            "splrSts": "08"

        };
        if (canClick == true) {
            canClick = false;
            $.ajax({
                url: HOST_ADDR + `/cpmp/splrMng/changeStsForSplr`,
                type: 'post',
                dataType: 'json',
                data: JSON.stringify(data),
                headers: {
                    'access_token': token,
                    'splrId': splrId,
                    'login_type': 'ums'
                },
                contentType: "application/json",
                success: function(resp) {
                    if (resp.success) {
                        alert('操作成功');
                        canClick = true;
                        location.href = '/supplier_mng/supplier_apply_list_mng.html';
                    } else {
                        canClick = true;
                        alert(resp.msgInf);
                        location.href = '/supplier_mng/supplier_apply_list_mng.html';

                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });


        }
        console.log('clicked');
    })


});